package com.gin.no_gay_alliance.activity;

import android.app.DatePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Message;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.gin.common.utils.TimeUtils;
import com.gin.no_gay_alliance.R;
import com.gin.no_gay_alliance.customview.PagerButton;
import com.gin.no_gay_alliance.database.entity.ReplyHistory;
import com.gin.no_gay_alliance.database.where.ReplyHistoryWhere;
import com.gin.no_gay_alliance.databinding.ActivityReplyHistorySearchBinding;
import com.gin.no_gay_alliance.databinding.DialogReplyHistorySearchBinding;
import com.gin.no_gay_alliance.enums.MessageWhat;
import com.gin.no_gay_alliance.fragment.history.ReplyHistorySearchPageFragment;
import com.gin.no_gay_alliance.utils.AlertDialogUtils;
import com.gin.no_gay_alliance.utils.EditTextUtils;
import com.gin.no_gay_alliance.viewmodel.PageData;

import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.concurrent.TimeUnit;

/**
 * 回复历史 - 搜索
 *
 * @author : ginstone
 * @version : v1.0.0
 * @since : 2023/9/18 16:39
 **/
public class ReplyHistorySearchActivity extends BaseBindingActivity<ActivityReplyHistorySearchBinding> implements TextView.OnEditorActionListener, PagerButton.OnPageChangedListener {
    ReplyHistoryWhere replyHistoryWhere;
    /**
     * 总页数
     */
    int totalPage = 1;
    private ReplyHistoryWhere dialogWhere;

    /**
     * 解析意图
     *
     * @param intent 意图
     */
    @Override
    protected void handleIntent(Intent intent) {

    }

    /**
     * onCreate中的后续操作
     */
    @Override
    protected void onCreate() {
        replyHistoryWhere = new ReplyHistoryWhere();

        updateFilterDescription();

        b.vp2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                b.btnPager.setData(position + 1, totalPage);
            }
        });
        //翻页器
        b.btnPager.init(this, handler, this);

        // 绑定软键盘搜索键
        b.et.setOnEditorActionListener(this);
        // 关键字输入框自动聚焦
        EditTextUtils.focusSelect(this, b.et, handler);
    }

    /**
     * 装载右上角菜单
     *
     * @param menu         菜单
     * @param menuInflater 菜单渲染器
     */
    @Override
    protected void onCreateOptionsMenu(Menu menu, MenuInflater menuInflater) {
        menuInflater.inflate(R.menu.reply_history_search_menu, menu);
    }

    /**
     * 处理消息
     *
     * @param message 消息
     * @return 是否消耗该消息
     */
    @Override
    public boolean handleMessage(@NonNull Message message) {
        // 查询成功
        if (message.what == MessageWhat.ON_SUCCESS_REPLY_HISTORY_PAGE.ordinal()) {
            PageData<ReplyHistory> pageData = (PageData<ReplyHistory>) message.obj;
            this.totalPage = pageData.totalPage;

            b.btnPager.setData(pageData.page, pageData.totalPage);
        }

        return super.handleMessage(message);
    }

    @Override
    protected Toolbar initToolbar() {
        return b.toolbar;
    }


    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        // 当按下软键盘搜索键时，执行搜索
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            // 执行搜索
            sendRequest();
            return true;
        }
        return false;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        // 弹窗修改查询条件
        if (item.getItemId() == R.id.menu_item_filter) {
            showFilterDialog();
            return true;
        }
        // 执行查询
        if (item.getItemId() == R.id.menu_item_search) {
            sendRequest();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * 翻页器执行翻页操作时的回调
     *
     * @param page 目标页数
     */
    @Override
    public void onPageChanged(int page) {
        b.vp2.setCurrentItem(page - 1, false);
    }

    /**
     * 执行搜索
     */
    private void sendRequest() {
        replyHistoryWhere.keyword = b.et.getText().toString();
        b.vp2.setAdapter(new FragmentStateAdapter(this) {
            @NonNull
            @Override
            public Fragment createFragment(int position) {
                return ReplyHistorySearchPageFragment.newInstance(replyHistoryWhere, position + 1);
            }

            @Override
            public int getItemCount() {
                return totalPage;
            }
        });

    }

    /**
     * 显示查群条件弹窗
     */
    private void showFilterDialog() {
        // 复制一份参数
        dialogWhere = replyHistoryWhere.clone();

        DialogReplyHistorySearchBinding b = DialogReplyHistorySearchBinding.inflate(getLayoutInflater());

        // 初始化弹窗状态
        if (dialogWhere.start != null) {
            b.tvValueStart.setText(TimeUtils.format(dialogWhere.start, TimeUnit.SECONDS, TimeUtils.DATE_FORMATTER));
        }
        if (dialogWhere.end != null) {
            b.tvValueEnd.setText(TimeUtils.format(dialogWhere.end, TimeUnit.SECONDS, TimeUtils.DATE_FORMATTER));
        }
        b.etUsername.setText(dialogWhere.username);
        b.rgLogic.check(dialogWhere.logic == ReplyHistoryWhere.LOGIC_AND ? R.id.rb_and : R.id.rb_or);
        if (dialogWhere.hasImage != null) {
            b.rgImage.check(dialogWhere.hasImage ? R.id.rb_true : R.id.rb_false);
        } else {
            b.rgImage.check(R.id.rb_null);
        }
        // 点击打开弹窗设置日期
        b.tvValueStart.setOnClickListener(v -> {
            ZonedDateTime zdt = dialogWhere.start == null ? ZonedDateTime.now() : ZonedDateTime.ofInstant(Instant.ofEpochSecond(dialogWhere.start), ZoneId.systemDefault());
            new DatePickerDialog(this, (view, year, month, dayOfMonth) -> {
                dialogWhere.start = ZonedDateTime.of(year, month + 1, dayOfMonth, 0, 0, 0, 0, ZoneId.systemDefault()).toEpochSecond();
                b.tvValueStart.setText(TimeUtils.format(dialogWhere.start, TimeUnit.SECONDS, TimeUtils.DATE_FORMATTER));
            }, zdt.getYear(), zdt.getMonthValue() - 1, zdt.getDayOfMonth()).show();
        });
        // 点击打开弹窗设置日期
        b.tvValueEnd.setOnClickListener(v -> {
            ZonedDateTime zdt = dialogWhere.end == null ? ZonedDateTime.now() : ZonedDateTime.ofInstant(Instant.ofEpochSecond(dialogWhere.end), ZoneId.systemDefault());
            new DatePickerDialog(this, (view, year, month, dayOfMonth) -> {
                dialogWhere.end = ZonedDateTime.of(year, month + 1, dayOfMonth, 23, 59, 59, 0, ZoneId.systemDefault()).toEpochSecond();
                b.tvValueEnd.setText(TimeUtils.format(dialogWhere.end, TimeUnit.SECONDS, TimeUtils.DATE_FORMATTER));
            }, zdt.getYear(), zdt.getMonthValue() - 1, zdt.getDayOfMonth()).show();
        });


        AlertDialogUtils.showConfirm(this, "查询条件", null, b.getRoot(), (d, which) -> {
            if (which == DialogInterface.BUTTON_POSITIVE) {
                dialogWhere.username = b.etUsername.getText().toString();
                dialogWhere.logic = b.rgLogic.getCheckedRadioButtonId() == R.id.rb_and ? ReplyHistoryWhere.LOGIC_AND : ReplyHistoryWhere.LOGIC_OR;

                if (b.rgImage.getCheckedRadioButtonId() == R.id.rb_null) {
                    dialogWhere.hasImage = null;
                } else {
                    dialogWhere.hasImage = b.rgImage.getCheckedRadioButtonId() == R.id.rb_true;
                }
                // 应用条件
                replyHistoryWhere = dialogWhere.clone();
                updateFilterDescription();
                sendRequest();
            }
        });
    }

    /**
     * 更新查询条件表述
     */
    private void updateFilterDescription() {
        b.tvFilter.setText(replyHistoryWhere.buildDescription());
    }

    public static void startActivity(Context context) {
        context.startActivity(new Intent(context, ReplyHistorySearchActivity.class));
    }
}
